// app.js
App({
  fetch: require('./utils/fetch.js'),
  onUserLoginReady: false,
  userLoginReadyCallBack: null,
  onLaunch: function(){
    wx.showLoading({
      title: "登录中",
      mask: true
    })
    this.fetch('/user/checkLogin').then(data => {
      if(data.isLogin){
        //已登录
        this.onUserLoginReady()
        console.log('通过保存的Cookie登录成功');
      }else{
        //未登录
        this.login({
          success: () => {
            this.onUserLoginReady()
          },
          fail: () => {
            console.log('未登录');
          }
        })
      }
    },() => {
      this.onLaunch()
    })
  },
  login: function(options) {
    //成功时调用options.success()
    //失败时调用options.fail()
    wx.login({
      success: res  => {
        this.fetch('/user/login',{
          js_code: res.code
        }).then(data => {
          if(data && data.isLogin){
            options.success()
          }else{
            wx.hideLoading()
            wx.showModal({
              title: '登录失败（请使用真是的AppID，并检查服务器端配置',
              confirmText: '重试',
              success: res => {
                if(res.confirm){
                  options.fail()
                }
              }
            })
          }
        },() => {
          options.fail()
        })
      }
    })
  },
  onUserLoginReady: function() {
    wx.hideLoading()
    if(this.userLoginReadyCallBack) {
      this.userLoginReadyCallBack()
    }
    this.userLoginReady = true
    //console.log('已登录');
  }
})
